use crate::game_state::{GameScene, GameState};
use crate::scenes::game_common::{debug_mode, generate_coins, generate_hearts, get_dynamic_params, handle_collisions, move_cars, move_coins, move_hearts, move_player, move_road_elements, pause_display, toggle_pause, LANES, MUSIC_TRACKS, PLAYER_SPEED, ROAD_SPEED, SAFE_DISTANCE};
use crate::scenes::switch_scene;
use crate::{CHARACTER_LAYER, UI_TOP_LAYER};
use rand::prelude::IndexedRandom;
use rand::Rng;
use rusty_engine::prelude::*;

pub fn logic(engine: &mut Engine, game_state: &mut GameState) {
    // 初始化游戏场景
    if !game_state.game_double_init {
        init_game_play(engine, game_state);
        game_state.game_double_init = true;
    }

    // 游戏结束
    if game_state.lost[0] && game_state.lost[1]{
        switch_scene(game_state, GameScene::GameOver)
    }

    debug_mode(engine, game_state);
    
    // 处理暂停功能
    if engine.keyboard_state.just_pressed(KeyCode::P) {
        toggle_pause(engine, game_state);
    }

    // 暂停显示
    pause_display(engine, game_state);

    // 如果游戏暂停，跳过后续逻辑
    if game_state.stop == false {
        // 更新无敌计时器
        if game_state.hit[0] {
            game_state.hit_timer[0].tick(engine.delta);
            if game_state.hit_timer[0].finished() {
                game_state.hit[0] = false;
                game_state.hit_timer[0].reset();
            }
        }
        if game_state.hit[1] {
            game_state.hit_timer[1].tick(engine.delta);
            if game_state.hit_timer[1].finished() {
                game_state.hit[1] = false;
                game_state.hit_timer[1].reset();
            }
        }

        // 玩家移动控制
        handle_player_movement(engine, game_state);

        // 移动道路元素
        move_road_elements(engine);

        // 车辆生成
        generate_cars(engine, game_state);

        // 车辆移动
        move_cars(engine, game_state);

        // 金币生成
        generate_coins(engine);

        // 金币移动
        move_coins(engine);

        // 爱心生成
        generate_hearts(engine, game_state);

        // 爱心移动
        move_hearts(engine);

        // 处理碰撞
        handle_collisions(engine, game_state);

        // 处理死去的玩家
        if game_state.lost[0] == true {
            engine.sprites.remove("player1");
        } else if game_state.lost[1] == true {
            engine.sprites.remove("player2");
        }

        // 距离累计
        add_distance(engine, game_state);

        // 得分计算
        add_score(game_state);

        // 如果没有在播放音乐，随机播放音乐
        if engine.audio_manager.music_playing() == false {
            let random_track : &str = MUSIC_TRACKS
                .choose(&mut rand::rng())
                .expect("音乐列表不应为空");

            engine.audio_manager.play_music(random_track, 0.5);
        }
    }
}

fn init_game_play(engine: &mut Engine, game_state: &mut GameState) {
    // 将其他界面初始化设置为false，避免发生错误
    game_state.main_menu_init = false;
    game_state.game_over_init = false;
    game_state.game_single_init = false;

    // 停止主菜单界面音乐，随机播放一首游戏音乐
    engine.audio_manager.stop_music();

    let random_track : &str = MUSIC_TRACKS
        .choose(&mut rand::rng())
        .expect("音乐列表不应为空");

    engine.audio_manager.play_music(random_track, 0.5);

    // 重置游戏状态
    game_state.health_amount[0] = 5;
    game_state.coins[0] = 0;
    game_state.distance[0] = 0.0;
    game_state.hit[0] = false;
    game_state.lost[0] = false;
    game_state.hit_timer[0].reset();
    game_state.score[0] = 0;

    game_state.health_amount[1] = 5;
    game_state.coins[1] = 0;
    game_state.distance[1] = 0.0;
    game_state.hit[1] = false;
    game_state.lost[1] = false;
    game_state.hit_timer[1].reset();
    game_state.score[1] = 0;

    // 清除主菜单元素
    engine.sprites.clear();
    engine.texts.clear();

    // 创建玩家
    let player1 = engine.add_sprite("player1", "sprite/racing/car_blue.png");
    player1.translation.x = -500.0;
    player1.translation.y = 90.0;
    player1.layer = CHARACTER_LAYER;
    player1.collision = true;
    player1.scale = 1.0;

    let player2 = engine.add_sprite("player2", "sprite/racing/car_pink.png");
    player2.translation.x = -500.0;
    player2.translation.y = -90.0;
    player2.layer = CHARACTER_LAYER;
    player2.collision = true;
    player2.scale = 1.0;

    // 创建道路标记
    for i in 0..10 {
        let roadline = engine.add_sprite(format!("roadline{}", i), "sprite/racing/barrier_white.png");
        roadline.scale = 0.1;
        roadline.translation.x = -600.0 + 150.0 * i as f32;
        roadline.translation.y = 180.0;

        let roadline = engine.add_sprite(format!("roadline{}", i + 11), "sprite/racing/barrier_white.png");
        roadline.scale = 0.1;
        roadline.translation.x = -600.0 + 150.0 * i as f32;
        roadline.translation.y = -180.0;
    }

    let roadline = engine.add_sprite("center_line", "sprite/racing/barrier_long.png");
    roadline.scale = 0.1;
    roadline.translation.x = 0.0;
    roadline.translation.y = 0.0;

    let roadline = engine.add_sprite("up_line", "sprite/racing/barrier_long.png");
    roadline.scale = 0.1;
    roadline.translation.x = 0.0;
    roadline.translation.y = 360.0;

    let roadline = engine.add_sprite("down_line", "sprite/racing/barrier_long.png");
    roadline.scale = 0.1;
    roadline.translation.x = 0.0;
    roadline.translation.y = -360.0;

    // 创建生命值显示
    let health_message = engine.add_text("health_0_message", "生命值: 5");
    health_message.translation = Vec2::new(560.0, 340.0);
    health_message.font_size = 22.0;
    health_message.layer = UI_TOP_LAYER;
    health_message.font = "font/HYPixel11pxU-2.ttf".to_string();
    // 创建当前距离显示
    let distance_message = engine.add_text("distance_0_message", "距离: 0.0");
    distance_message.translation = Vec2::new(560.0, 318.0);
    distance_message.font_size = 22.0;
    distance_message.layer = UI_TOP_LAYER;
    distance_message.font = "font/HYPixel11pxU-2.ttf".to_string();
    // 创建当前金币数显示
    let coin_message = engine.add_text("coin_0_message", "金币数: 0");
    coin_message.translation = Vec2::new(560.0, 296.0);
    coin_message.font_size = 22.0;
    coin_message.layer = UI_TOP_LAYER;
    coin_message.font = "font/HYPixel11pxU-2.ttf".to_string();

    // 创建生命值显示
    let health_message = engine.add_text("health_1_message", "生命值: 5");
    health_message.translation = Vec2::new(-580.0, 340.0);
    health_message.font_size = 22.0;
    health_message.layer = UI_TOP_LAYER;
    health_message.font = "font/HYPixel11pxU-2.ttf".to_string();
    // 创建当前距离显示
    let distance_message = engine.add_text("distance_1_message", "距离: 0.0");
    distance_message.translation = Vec2::new(-580.0, 318.0);
    distance_message.font_size = 22.0;
    distance_message.layer = UI_TOP_LAYER;
    distance_message.font = "font/HYPixel11pxU-2.ttf".to_string();
    // 创建当前金币数显示
    let coin_message = engine.add_text("coin_1_message", "金币数: 0");
    coin_message.translation = Vec2::new(-580.0, 296.0);
    coin_message.font_size = 22.0;
    coin_message.layer = UI_TOP_LAYER;
    coin_message.font = "font/HYPixel11pxU-2.ttf".to_string();
}

fn add_score(game_state : &mut GameState) {
    game_state.score[0] = (game_state.distance[0] * 0.01) as u32 + game_state.coins[0] * 10;
    game_state.score[1] = (game_state.distance[1] * 0.01) as u32 + game_state.coins[1] * 10;
}

fn add_distance(engine: &mut Engine, game_state: &mut GameState) {
    if game_state.lost[0] == false {
        game_state.distance[0] += 120.0 * ROAD_SPEED / (400.0 * 360.0);
        let distance_message = engine.texts.get_mut("distance_0_message").unwrap();
        distance_message.value = format!("距离: {}", game_state.distance[0] as i32);
    }
    if game_state.lost[1] == false {
        game_state.distance[1] += 120.0 * ROAD_SPEED / (400.0 * 360.0);
        let distance_message = engine.texts.get_mut("distance_1_message").unwrap();
        distance_message.value = format!("距离: {}", game_state.distance[1] as i32);
    }
}

fn handle_player_movement(engine: &mut Engine, game_state: &mut GameState) {
    let mut direction_0 : Vec2 = Vec2::new(0.0,0.0);
    let mut direction_1 : Vec2 = Vec2::new(0.0,0.0);

    // 玩家速度增长因子，只取决于金币数
    let player_speed_factor_0 = game_state.coins[0] as f32 * 0.01;
    let player_speed_factor_1 = game_state.coins[1] as f32 * 0.01;

    // 玩家1键盘控制
    if engine.keyboard_state.pressed_any(&[KeyCode::W]) {
        direction_0.y += 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::S]) {
        direction_0.y -= 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::A]) {
        direction_0.x -= 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::D]) {
        direction_0.x += 1.0;
    }

    // 玩家2键盘控制
    if engine.keyboard_state.pressed_any(&[KeyCode::Up]) {
        direction_1.y += 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::Down]) {
        direction_1.y -= 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::Left]) {
        direction_1.x -= 1.0;
    }
    if engine.keyboard_state.pressed_any(&[KeyCode::Right]) {
        direction_1.x += 1.0;
    }

    let speed0 = PLAYER_SPEED * engine.delta_f32 * (1.0 + player_speed_factor_0);
    let speed1 = PLAYER_SPEED * engine.delta_f32 * (1.0 + player_speed_factor_1);
    // 移动玩家1
    move_player(engine, "player1", speed0, direction_0);
    // 移动玩家2
    move_player(engine, "player2", speed1, direction_1);
}

fn generate_cars(engine: &mut Engine, game_state: &mut GameState) {
    // 获取车辆数量
    let mut car_count_0 = 0;
    let mut car_count_1 = 0;
    for (label, sprite) in engine.sprites.iter_mut() {
        // 分开计数
        if label.starts_with("car_") {
            if sprite.translation.y < 0.0 {
                car_count_0 += 1;
            } else {
                car_count_1 += 1;
            }
        }
    }

    // 获取动态参数
    let (spawn_prob, max_cars, speed_factor) = get_dynamic_params(game_state);

    // 如果满足生成条件，就试图生成车辆
    // 下车道
    if car_count_0 < max_cars / 2 && game_state.distance[0] >= 100.0 {
        // 动态概率生成新车
        if rand::rng().random_range(0.0..1.0) < spawn_prob {
            // 只能是下车道
            let lane_idx = rand::rng().random_range(2..4);
            let lane_y = LANES[lane_idx];

            // 检查是否安全并且生成车辆
            check_and_generate(engine, game_state, lane_y, speed_factor);
        }
    }
    // 上车道
    if car_count_1 < max_cars / 2 && game_state.distance[1] >= 100.0 {
        // 动态概率生成新车
        if rand::rng().random_range(0.0..1.0) < spawn_prob {
            // 只能是上车道
            let lane_idx = rand::rng().random_range(0..2);
            let lane_y = LANES[lane_idx];

            // 检查是否安全并且生成车辆
            check_and_generate(engine, game_state, lane_y, speed_factor);
        }
    }
}

// 检查是否安全并且生成车辆
fn check_and_generate(engine: &mut Engine, game_state: &mut GameState, lane_y : f32, speed_factor : f32) {
    // 检查该车道是否安全（没有其他车辆）
    let mut safe_to_spawn = true;

    for (_, sprite) in engine.sprites.iter() {
        if sprite.label.starts_with("car_") &&
            (sprite.translation.y - lane_y).abs() < 50.0 { // 同一车道

            // 检查距离是否安全
            if (sprite.translation.x - 750.0).abs() < SAFE_DISTANCE {
                safe_to_spawn = false;
                break;
            }
        }
    }

    if !safe_to_spawn {
        return; // 车道不安全，不生成车辆
    }

    // 随机偏移量，避免过于居中
    let y_offset = rand::rng().random_range(-40.0..40.0);
    let y_position = lane_y + y_offset;

    // 随机选择车辆颜色
    let car_colors = ["car_black", "car_green", "car_red", "car_yellow"];
    let car_color = car_colors[rand::rng().random_range(0..car_colors.len())];

    // 创建车辆精灵
    let car_id = format!("car_{}", rand::random::<u32>());
    let car = engine.add_sprite(&car_id, &format!("sprite/racing/{}.png", car_color));
    car.translation.x = 750.0; // 从屏幕右侧出现
    car.translation.y = y_position;
    car.scale = 1.0;
    car.layer = CHARACTER_LAYER;
    car.collision = true;

    let base_speed : f32 = rand::rng().random_range(400.0..600.0);
    let speed: f32 = base_speed * (1.0 + speed_factor).min(2.0);

    // 存储速度
    game_state.car_speeds.insert(car_id.clone(), speed);
}